console.log("buyertrade.js");

chrome.runtime.onMessage.addListener(
    function (request, sender, sendResponse) {
        if (request.type == "background_getUserId") {
            var order = request.order;
            var orderSn = request.orderSn;
            var times = request.times;
            getUserId(order, orderSn, times);

            sendResponse({farewell: "successful"});
        }
    });


function getUserId(order, orderSn, times) {
    var url = "https://buyertrade.taobao.com/trade/itemlist/asyncBought.htm?action=itemlist/BoughtQueryAction&event_submit_do_query=1&_input_charset=utf8";
    var params = {};
    params["pageNum"] = 1;
    params["pageSize"] = 15;
    params["auctionTitle"] = order;
    params["itemTitle"] = order;
    params["prePageNo"] = 1;

    $.ajax(url, {
        type: "POST",
        async: true,
        data: params,
        crossDomain: true,
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        //成功返回之后调用的函数
        success: function (data) {
            var userid = data.substring(data.indexOf("user_number_id"), data.indexOf("wangwangType"));
            userid = userid.substring(userid.indexOf("=") + 1, userid.indexOf("\""));
            console.log(data + "\nuserid " + userid + "\t order " + order + "\t orderSn " + orderSn);

            //给backround发消息,淘宝一键发货的按钮点击了
            chrome.runtime.sendMessage({
                type: "buyertrade_giveUserId",
                order: order,
                orderSn: orderSn,
                userid: userid,
                times: (times + 1)
            }, function (response) {
                if (response.canUse == false) {
                    alert("插件当前不可用\n请到配置页面配置!\n\n按空格键关闭提示");
                }
            });
        }
    });
}
